package platform

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/wzh200x/hyperNexus/hyperNexusErr"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/interfaceServerProtocol"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

// 微信登录返回的会话信息
type KuaiShouSession struct {
	OpenID     string `json:"open_id"`
	SessionKey string `json:"session_key"`
	Result     int32  `json:"result"`
	ErrorMsg   string `json:"error_msg"`
}

type PlatformKuaiShou struct {
	PlatformBase
}

func (p *PlatformKuaiShou) Login(ctx context.Context, input *interfaceServerProtocol.LoginRequest) (output interfaceServerProtocol.LoginResponse, err error) {
	// 1. 通过code获取微信会话信息
	session, err := p.GetSession(input.AppId, input.AppSecret, input.Code)
	if err != nil {
		output.Code = hyperNexusErr.ErrCode_PlatformLoginFailed
		output.Msg = err.Error()
		return output, err
	}
	output.Code = 0
	output.OpenId = session.OpenID
	output.Datas = session.SessionKey

	return output, nil
}

// 通过code获取微信会话信息
func (p *PlatformKuaiShou) GetSession(appid string, appSecret string, code string) (*KuaiShouSession, error) {
	url := fmt.Sprintf("https://open.kuaishou.com/game/minigame/jscode2session?app_id=%s&app_secret=%s&js_code=%s&grant_type=authorization_code",
		appid, appSecret, code)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var session KuaiShouSession
	if err := json.Unmarshal(body, &session); err != nil {
		return nil, err
	}

	if session.Result != 1 {
		return nil, fmt.Errorf("快手API错误: %d ", session.Result)
	}

	return &session, nil
}

func NewPlatformKuaiShou() *PlatformKuaiShou {
	return &PlatformKuaiShou{
		PlatformBase: PlatformBase{
			PlatformID: hyperNexusType.PlatformTypeKuaiShou,
		},
	}
}
